"use client"

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { useEffect, useMemo, useRef } from "react"
import * as echarts from "echarts"
import { LazyChart } from "./LazyLoader"
import {
  IconActivity,
  IconMap,
  IconUsers,
  IconRefresh,
  IconDownload,
  IconPlay,
  IconPause,
  IconTrendingUp,
  IconTrendingDown,
  IconChartBar,
  IconBed,
  IconAlertTriangle
} from "@tabler/icons-react"

// 基础 ECharts 容器
function EChartBase({ option, className }: { option: echarts.EChartsOption; className?: string }) {
  const ref = useRef<HTMLDivElement | null>(null)
  useEffect(() => {
    if (!ref.current) return
    const chart = echarts.init(ref.current)
    chart.setOption(option)

    // 监听窗口大小变化和全屏变化
    const onResize = () => {
      if (chart && !chart.isDisposed()) {
        chart.resize()
      }
    }

    // 监听全屏变化
    const onFullscreenChange = () => {
      setTimeout(() => {
        if (chart && !chart.isDisposed()) {
          chart.resize()
        }
      }, 100)
    }

    window.addEventListener('resize', onResize)
    document.addEventListener('fullscreenchange', onFullscreenChange)

    return () => {
      window.removeEventListener('resize', onResize)
      document.removeEventListener('fullscreenchange', onFullscreenChange)
      chart.dispose()
    }
  }, [option])

  return <div ref={ref} className={className || "w-full h-72"} />
}

// 热力图组件（带懒加载）
const OptimizedHeatmapChart = () => {
  const gridSizeX = 20
  const gridSizeY = 15
  const data = useMemo(() => {
    const d: [number, number, number][] = []
    for (let x = 0; x < gridSizeX; x++) {
      for (let y = 0; y < gridSizeY; y++) {
        d.push([x, y, Math.round(Math.sin(x / 10) * Math.cos(y / 10) * 50 + 50)])
      }
    }
    return d
  }, [])

  const option: echarts.EChartsOption = {
    grid: { left: 20, right: 10, top: 10, bottom: 25 },
    tooltip: { position: 'top' },
    xAxis: { type: 'category', data: Array.from({ length: gridSizeX }, (_, i) => i), splitArea: { show: true } },
    yAxis: { type: 'category', data: Array.from({ length: gridSizeY }, (_, i) => i), splitArea: { show: true } },
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: 0
    },
    series: [
      {
        name: '密度',
        type: 'heatmap',
        data,
        emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.4)' } },
        progressive: 0
      }
    ]
  }

  return (
    <LazyChart className="chart-container w-full h-full">
      <EChartBase option={option} className="w-full h-full" />
    </LazyChart>
  )
}

// 趋势图表组件（带懒加载）
const OptimizedTrendChart = () => {
  const data = useMemo(() => {
    const dates = []
    const values = []
    const now = new Date()

    for (let i = 23; i >= 0; i--) {
      const date = new Date(now.getTime() - i * 60 * 60 * 1000)
      dates.push(date.getHours() + ':00')
      values.push(Math.round(Math.sin(i / 24 * Math.PI * 2) * 30 + 50))
    }

    return { dates, values }
  }, [])

  const option: echarts.EChartsOption = {
    grid: { left: 20, right: 20, top: 20, bottom: 20 },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: data.dates },
    yAxis: { type: 'value' },
    series: [
      {
        name: '人流量',
        type: 'line',
        data: data.values,
        smooth: true,
        lineStyle: { color: '#3b82f6' },
        areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [{ offset: 0, color: 'rgba(59, 130, 246, 0.3)' }, { offset: 1, color: 'rgba(59, 130, 246, 0.05)' }] } }
      }
    ]
  }

  return (
    <LazyChart className="chart-container w-full h-full">
      <EChartBase option={option} className="w-full h-full" />
    </LazyChart>
  )
}

// 设备利用率图表（带懒加载）
const OptimizedUtilizationChart = () => {
  const data = useMemo(() => {
    const devices = ['CT机', 'MRI', 'X光机', '超声', '心电图', '呼吸机']
    return devices.map(device => ({
      name: device,
      value: Math.round(Math.sin(index / 5 * Math.PI) * 40 + 60)
    }))
  }, [])

  const option: echarts.EChartsOption = {
    grid: { left: 20, right: 20, top: 20, bottom: 20 },
    tooltip: { trigger: 'item' },
    series: [
      {
        name: '设备利用率',
        type: 'pie',
        radius: ['40%', '70%'],
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  return (
    <LazyChart className="chart-container w-full h-full">
      <EChartBase option={option} className="w-full h-full" />
    </LazyChart>
  )
}

// 病床使用率图表（带懒加载）
const OptimizedBedUtilizationChart = () => {
  const data = useMemo(() => {
    const departments = ['内科', '外科', '儿科', '妇产科', '急诊科', 'ICU']
    return departments.map(dept => ({
      name: dept,
      value: Math.round(Math.sin(index / 5 * Math.PI) * 40 + 60)
    }))
  }, [])

  const option: echarts.EChartsOption = {
    grid: { left: 20, right: 20, top: 20, bottom: 20 },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: data.map(d => d.name) },
    yAxis: { type: 'value', max: 100 },
    series: [
      {
        name: '使用率',
        type: 'bar',
        data: data.map(d => d.value),
        itemStyle: {
          color: (params: any) => {
            const value = params.value
            if (value > 80) return '#ef4444'
            if (value > 60) return '#f59e0b'
            return '#10b981'
          }
        }
      }
    ]
  }

  return (
    <LazyChart className="chart-container w-full h-full">
      <EChartBase option={option} className="w-full h-full" />
    </LazyChart>
  )
}

// 预警统计图表（带懒加载）
const OptimizedAlertChart = () => {
  const alerts = useMemo(() => [
    { type: '设备故障', count: 3, level: 'high' },
    { type: '人员异常', count: 2, level: 'medium' },
    { type: '环境异常', count: 1, level: 'low' },
    { type: '系统警告', count: 4, level: 'medium' }
  ], [])

  return (
    <LazyChart className="w-full">
      <div className="space-y-4">
        {alerts.map((alert, index) => {
          const levelColors = {
            high: 'bg-red-100 text-red-800 border-red-200',
            medium: 'bg-yellow-100 text-yellow-800 border-yellow-200',
            low: 'bg-green-100 text-green-800 border-green-200'
          }

          return (
            <div key={index} className="flex items-center justify-between p-4 border rounded-lg">
              <div className="flex items-center space-x-3">
                <div className={`w-3 h-3 rounded-full ${alert.level === 'high' ? 'bg-red-500' :
                  alert.level === 'medium' ? 'bg-yellow-500' : 'bg-green-500'
                  }`}></div>
                <span className="font-medium">{alert.type}</span>
              </div>
              <div className={`px-3 py-1 rounded-full text-sm font-semibold border ${levelColors[alert.level as keyof typeof levelColors]}`}>
                {alert.count}
              </div>
            </div>
          )
        })}
      </div>
    </LazyChart>
  )
}

// 导出优化后的图表组件
export {
  OptimizedHeatmapChart as HeatmapChart,
  OptimizedTrendChart as TrendChart,
  OptimizedUtilizationChart as UtilizationChart,
  OptimizedBedUtilizationChart as BedUtilizationChart,
  OptimizedAlertChart as AlertChart
}
